package com.zecan.blog.controller;

import com.zecan.blog.common.BlogResult;
import com.zecan.blog.controller.exception.UserException;
import com.zecan.blog.entity.Tag;
import com.zecan.blog.service.TagService;
import com.zecan.blog.utils.BlogResultUtils;
import com.zecan.blog.vo.article.ArticleMsgVo;
import com.zecan.blog.vo.tag.TagMsgVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName TagController
 * @Description
 * @date 2022/11/3 21:38
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/tag")
public class TagController {

    @Resource
    private TagService service;

    /**
     * 获取标签信息
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public BlogResult getTagList() {

        List<Tag> tagListAll = service.getTagListAll();
        return BlogResultUtils.ok(tagListAll,"获取标签列表成功");
    }

    @RequestMapping(value = "/listCount",method = RequestMethod.GET)
    public BlogResult getTagListCount() {
        return BlogResultUtils.ok(service.getTagListCount(),"获取标签列表数量成功");
    }

    /**
     * 根据标签id集合获取文章信息
     * @param tagIds
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/tagByIdToArticle",method = RequestMethod.GET)
    public BlogResult getTagByIdToArticle(String tagIds,Integer offset ,Integer limit) {
        TagMsgVo tagMsgVo = service.selectArticleByTagId(tagIds, offset, limit);
        return BlogResultUtils.ok(tagMsgVo,"根据标签id获取文章信息成功");
    }

    /**
     * 修改标签内容
     * @param tagId id
     * @param newTagName name
     * @return
     */
    @PreAuthorize("hasAnyAuthority('admin')")
    @RequestMapping(value = "/update_tagName",method = RequestMethod.GET)
    public BlogResult updateTagName(Integer tagId,String newTagName) {

        if(tagId == null && newTagName == null) {
            return BlogResultUtils.exception(UserException.builder().msg("内容为空").build());
        }

        if(tagId == null) {
            service.insertTag(newTagName);
            return BlogResultUtils.ok("新增标签成功");
        }else {
            service.updateTagName(tagId, newTagName);
            return BlogResultUtils.ok("修改标签信息成功");
        }

    }


    /**
     * 删除标签
     * @param tagId id
     * @return
     */
    @PreAuthorize("hasAnyAuthority('admin')")
    @RequestMapping(value = "/delete_tag",method = RequestMethod.POST)
    public BlogResult deleteTag(Integer tagId) {
        service.deleteTag(tagId);
        return BlogResultUtils.ok("删除标签成功");
    }

}
